package top.zywork.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.zywork.common.BeanUtils;
import top.zywork.dao.GoodsExpressDAO;
import top.zywork.dos.GoodsExpressDO;
import top.zywork.dto.*;
import top.zywork.enums.ActiveStatusEnum;
import top.zywork.enums.ResponseStatusEnum;
import top.zywork.query.*;
import top.zywork.service.*;
import top.zywork.vo.ExpressComputeVO;
import top.zywork.vo.ResponseStatusVO;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * GoodsExpressServiceImpl服务接口实现类<br/>
 *
 * 创建于2019-11-22<br/>
 *
 * @author http://zywork.top 危锦辉
 * @version 1.0
 */
@Service(value = "goodsExpressService")
public class GoodsExpressServiceImpl extends AbstractBaseService implements GoodsExpressService {

    private GoodsExpressDAO goodsExpressDAO;

    private GoodsInfoService goodsInfoService;

    private ExpressTemplateService expressTemplateService;

    private ExpressTemplateItemService expressTemplateItemService;

    private GoodsSkuService goodsSkuService;

    private ShippingAddressService shippingAddressService;

    @Override
    public ResponseStatusVO saveData(Long goodsInfoId, Long expressTemplateId) {
        Object goodsInfoObj = goodsInfoService.getById(goodsInfoId);
        if (null == goodsInfoObj) {
            return ResponseStatusVO.error("商品不存在", null);
        }
        Object expressTemplateObj = expressTemplateService.getById(expressTemplateId);
        if (null == expressTemplateObj) {
            return ResponseStatusVO.error("运费模版不存在", null);
        }
        GoodsSkuQuery goodsSkuQuery = GoodsSkuQuery.builder().goodsId(goodsInfoId).isActive(ActiveStatusEnum.ACTIVE.getValue().byteValue()).build();
        List<Object> goodsSkuObjList = goodsSkuService.listAllByCondition(goodsSkuQuery).getRows();
        if (goodsSkuObjList.isEmpty()) {
            return ResponseStatusVO.error("该商品未配置sku", null);
        }
        List<GoodsExpressDTO> goodsExpressDTOList = new ArrayList<>();
        List<GoodsSkuDTO> goodsSkuDTOList = BeanUtils.copy(goodsSkuObjList, GoodsSkuDTO.class);
        for (GoodsSkuDTO goodsSkuDTO : goodsSkuDTOList) {
            GoodsExpressDTO goodsExpressDTO = GoodsExpressDTO.builder().goodsId(goodsInfoId).goodsSkuId(goodsSkuDTO.getId()).expressTemplateId(expressTemplateId).build();
            goodsExpressDTOList.add(goodsExpressDTO);
        }
        // 先删除该商品的所有运费配置
        goodsExpressDAO.removeByGoodsId(goodsInfoId);
        long saveRows = saveBatch(BeanUtils.copyListObj(goodsExpressDTOList, GoodsExpressDTO.class));
        if (saveRows <= 0) {
            return ResponseStatusVO.error("保存商品运费模板失败", null);
        }
        return ResponseStatusVO.ok("保存商品运费模板成功", null);
    }

    @Override
    public ResponseStatusVO getExpressInfoByUserId(Long userId, Long goodsId, Long goodsSkuId, String province) {
        ResponseStatusVO tempRes = getExpressInfo(goodsId, goodsSkuId);
        if (!"返回商品运费模版".equals(tempRes.getMessage())) {
            return tempRes;
        }
        // 该商品的sku有设置模版
        ExpressTemplateDTO expressTemplateDTO = BeanUtils.copy(tempRes.getData(), ExpressTemplateDTO.class);
        if (StringUtils.isEmpty(province)) {
            ShippingAddressQuery shippingAddressQuery = ShippingAddressQuery.builder().userId(userId).isActive((byte)0).isDefault((byte)1).build();
            List<Object> shippingAddressObjList = shippingAddressService.listAllByCondition(shippingAddressQuery).getRows();
            if (shippingAddressObjList.isEmpty()) {
                // 该用户没有设置默认地址信息
                return ResponseStatusVO.ok("返回商品运费模版", expressTemplateDTO);
            }
            ShippingAddressDTO shippingAddressDTO = BeanUtils.copy(shippingAddressObjList.get(0), ShippingAddressDTO.class);
            province = shippingAddressDTO.getProvince();
        }
        ExpressTemplateItemQuery expressTemplateItemQuery = ExpressTemplateItemQuery.builder().templateId(expressTemplateDTO.getId()).province(province).isActive((byte)0).build();
        List<Object> expressTemplateItemObjList = expressTemplateItemService.listAllByCondition(expressTemplateItemQuery).getRows();
        if (expressTemplateItemObjList.isEmpty()) {
            // 未获取到地址对应的模版项配置
            return ResponseStatusVO.ok("返回商品运费模版", expressTemplateDTO);
        }
        ExpressTemplateItemDTO expressTemplateItemDTO = BeanUtils.copy(expressTemplateItemObjList.get(0), ExpressTemplateItemDTO.class);
        expressTemplateItemDTO.setExpressPlace(expressTemplateDTO.getExpressPlace());
        return ResponseStatusVO.ok("返回商品运费模版项", expressTemplateItemDTO);
    }

    @Override
    public ResponseStatusVO getExpressInfo(Long goodsId, Long goodsSkuId) {
        ResponseStatusVO tempRes = getDefaultExpressInfo();
        if (!"返回默认运费模版".equals(tempRes.getMessage())) {
            return tempRes;
        }
        // 默认模版配置
        ExpressTemplateDTO expressTemplateDTO = BeanUtils.copy(tempRes.getData(), ExpressTemplateDTO.class);
        GoodsExpressQuery goodsExpressQuery = GoodsExpressQuery.builder().goodsId(goodsId).goodsSkuId(goodsSkuId).isActive((byte)0).build();
        List<Object> goodsExpressQueryObjList = goodsExpressDAO.listAllByCondition(goodsExpressQuery);
        if (goodsExpressQueryObjList.isEmpty()) {
            return ResponseStatusVO.ok("返回默认运费模版", expressTemplateDTO);
        }
        GoodsExpressDTO goodsExpressDTO = BeanUtils.copy(goodsExpressQueryObjList.get(0), GoodsExpressDTO.class);
        Object expressTemplateObj = expressTemplateService.getById(goodsExpressDTO.getExpressTemplateId());
        expressTemplateDTO = BeanUtils.copy(expressTemplateObj, ExpressTemplateDTO.class);
        return ResponseStatusVO.ok("返回商品运费模版", expressTemplateDTO);
    }

    @Override
    public ResponseStatusVO getDefaultExpressInfo() {
        ExpressTemplateQuery expressTemplateQuery = ExpressTemplateQuery.builder().isDefault((byte)1).isActive(ActiveStatusEnum.ACTIVE.getValue().byteValue()).build();
        List<Object> expressTemplateObjList = expressTemplateService.listAllByCondition(expressTemplateQuery).getRows();
        if (expressTemplateObjList.isEmpty()) {
            return ResponseStatusVO.dataError("未配置默认运费模板", null);
        }
        // 默认模版配置
        ExpressTemplateDTO expressTemplateDTO = BeanUtils.copy(expressTemplateObjList.get(0), ExpressTemplateDTO.class);
        return ResponseStatusVO.ok("返回默认运费模版", expressTemplateDTO);
    }

    @Override
    public ResponseStatusVO computeExpressFee(Long userId, List<ExpressComputeVO> expressComputeVOList) {
        BigDecimal expressFee = new BigDecimal(0);
        BigDecimal zero = new BigDecimal(0);
        for (ExpressComputeVO expressComputeVO : expressComputeVOList) {
            ResponseStatusVO tempRes = getExpressInfoByUserId(userId, expressComputeVO.getGoodsId(), expressComputeVO.getSkuId(), expressComputeVO.getProvince());
            if (tempRes.getCode().intValue() != ResponseStatusEnum.OK.getCode().intValue()) {
                // 未配置默认运费
                return tempRes;
            }
            Long goodsCount = expressComputeVO.getGoodsCount();
            if (goodsCount == null || goodsCount <= 0) {
                return ResponseStatusVO.dataError("请检查商品数量，必须大于等于1", null);
            }
            BigDecimal totalCount = new BigDecimal(expressComputeVO.getGoodsCount());
            BigDecimal goodsPrice = expressComputeVO.getGoodsPrice();
            Object obj = tempRes.getData();
            BigDecimal incrementSpec = zero;
            BigDecimal incrementFee = zero;
            BigDecimal freeCondition = zero;
            BigDecimal freeMaxPayment = zero;
            BigDecimal defaultExpressFee = zero;
            if ("返回商品运费模版项".equals(tempRes.getMessage())) {
                ExpressTemplateItemDTO expressTemplateItemDTO = BeanUtils.copy(obj, ExpressTemplateItemDTO.class);
                if (expressTemplateItemDTO.getExpressFree() == 0) {
                    // 包邮商品
                    continue;
                }
                freeCondition = expressTemplateItemDTO.getFreeCondition();
                freeMaxPayment = expressTemplateItemDTO.getFreeMaxPayment();
                incrementSpec = expressTemplateItemDTO.getIncrementSpec();
                incrementFee = expressTemplateItemDTO.getIncrementFee();
                defaultExpressFee = expressTemplateItemDTO.getExpressFee();
            } else {
                ExpressTemplateDTO expressTemplateDTO = BeanUtils.copy(obj, ExpressTemplateDTO.class);
                if (expressTemplateDTO.getExpressFree() == 0) {
                    // 包邮商品
                    continue;
                }
                freeCondition = expressTemplateDTO.getDefaultFreeCondition();
                freeMaxPayment = expressTemplateDTO.getDefaultFreeMaxPayment();
                incrementSpec = expressTemplateDTO.getDefaultIncrementSpec();
                incrementFee = expressTemplateDTO.getDefaultIncrementFee();
                defaultExpressFee = expressTemplateDTO.getDefaultFee();
            }
            if (null != freeCondition && freeCondition.compareTo(zero) != 0) {
                // 有设置包邮条件，达到指定的数量包邮
                if (totalCount.compareTo(freeCondition) >= 0) {
                    // 达到了包邮条件
                    continue;
                }
            }
            if (null != freeMaxPayment && freeMaxPayment.compareTo(zero) != 0) {
                // 有设置包邮条件，达到指定的金额包邮
                if (totalCount.compareTo(goodsPrice) > 0) {
                    // 达到了包邮条件
                    continue;
                }
            }
            if (incrementSpec.compareTo(zero) != 0 && incrementFee.compareTo(zero) != 0) {
                BigDecimal oneExpressFee = defaultExpressFee;
                if (totalCount.compareTo(new BigDecimal(1)) > 0) {
                    // 总数量大于1 递增运费 = ((总数量-1) / 递增规格) * 递增费用
                    totalCount = totalCount.subtract(new BigDecimal(1));
                    BigDecimal addExpressFee = totalCount.divide(incrementSpec, BigDecimal.ROUND_FLOOR).multiply(incrementFee);
                    oneExpressFee = oneExpressFee.add(addExpressFee);
                }
                expressFee = expressFee.add(oneExpressFee);
            }
        }
        return ResponseStatusVO.ok("订单运费计算成功", expressFee);
    }

    @Autowired
    public void setGoodsExpressDAO(GoodsExpressDAO goodsExpressDAO) {
        super.setBaseDAO(goodsExpressDAO);
        this.goodsExpressDAO = goodsExpressDAO;
    }

    @Autowired
    public void setGoodsInfoService(GoodsInfoService goodsInfoService) {
        this.goodsInfoService = goodsInfoService;
    }

    @Autowired
    public void setExpressTemplateService(ExpressTemplateService expressTemplateService) {
        this.expressTemplateService = expressTemplateService;
    }

    @Autowired
    public void setExpressTemplateItemService(ExpressTemplateItemService expressTemplateItemService) {
        this.expressTemplateItemService = expressTemplateItemService;
    }

    @Autowired
    public void setGoodsSkuService(GoodsSkuService goodsSkuService) {
        this.goodsSkuService = goodsSkuService;
    }

    @Autowired
    public void setShippingAddressService(ShippingAddressService shippingAddressService) {
        this.shippingAddressService = shippingAddressService;
    }

    @PostConstruct
    public void init() {
        super.init(GoodsExpressDO.class, GoodsExpressDTO.class);
    }

}
